package com.japhet.oss.oss.common.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.japhet.oss.oss.config.OSSBean;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

public class AliOSSUtil {
    public static final String bucketName = "xxx";//你的桶名
    public static final String nowPath = "http://xxxx.xxxx.com/test/test/";//你的域名
    private static OSS getOssClient(){
        return OSSBean.ossClient();
    }
    public static String uploadImg(MultipartFile file, int sizeLimit){
        OSS ossClient = getOssClient();
        Assert.isTrue("image".equals(Objects.requireNonNull(file.getContentType()).split("/")[0]), "图片格式异常");
        Assert.isTrue(file.getSize() <= 1024 * 1000 * sizeLimit, "文件不得大于" + sizeLimit + "M");
        String imgName = UUID.randomUUID().toString();
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        try {
            String[] filename = originalFilename.split("\\.");
            int randomNum = (int) (Math.random() * 900) + 100;
            File tempFile = File.createTempFile(filename[0].length()<=2?randomNum+"":filename[0], filename[1]);
            file.transferTo(tempFile);
            tempFile.deleteOnExit();
            ossClient.putObject(bucketName, "test/test/"+imgName+suffix , tempFile);
            ossClient.shutdown();
            System.out.println("上传图片完成！URL ====== "+nowPath+imgName+suffix);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return nowPath+imgName+suffix;
    }

}
